import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken, setRouterItem, removeRouterItem } from '@/utils/storage'
import { resetRouter } from '@/router'
import { md5 } from '@/utils/validate'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  // roles: [],
  user_id: '',
  router_id: [],
  cachedViews: [
    'news_create',
    'news_edit'
  ]
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  // SET_ROLES: (state, roles) => {
  //   state.roles = roles
  // },
  SET_ROUTER_ID: (state, routerId) => {
    state.router_id = routerId
  },
  SET_USER_ID: (state, userid) => {
    state.user_id = userid
  }
}

const actions = {
  // user login
  login ({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: md5(password) }).then(response => {
        const { token, views, username } = response
        setRouterItem(views)
        commit('SET_TOKEN', token)
        commit('SET_NAME', username)
        // commit('SET_ROUTER_ID', views);
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo ({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.name || 'admin').then(async response => {
        // const {username, userid, views, exp, roles, name, avatar} = data;

        if (!response) {
          reject('no response')
          throw new Error('get user Info no response')
        }
        const { username, userid, views } = response
        // 考虑 exp 设置到Cookie中 方便同步过期时间

        // roles must be a non-empty array
        if (!views || views.length <= 0) {
          reject('getInfo: views must be a non-null array!')
        }
        // commit('SET_ROLES', roles);
        commit('SET_NAME', username)
        commit('SET_USER_ID', userid)
        commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
        commit('SET_ROUTER_ID', views)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout ({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROUTER_ID', [])
        removeToken()
        resetRouter()
        removeRouterItem()
        resolve()
      }, 0)
      // logout(state.token).then(() => {
      //   commit('SET_TOKEN', '')
      //   commit('SET_ROLES', [])
      //   removeToken()
      //   resetRouter()
      //   removeRouterItem()
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken ({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      // commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  }

  // dynamically modify permissions
  /* changeRoles({commit, dispatch}, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const {roles} = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, {root: true})

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, {root: true})

      resolve()
    })
  } */
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
